package org.android.demo;

import java.util.ArrayList;

import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

/*
 * Used to display the Projects into a ListView
 */
public class ProjectAdapter extends BaseAdapter {
	private Activity context;
	private ArrayList<ProjectList> projects;

	public ProjectAdapter (Activity context) {
		this.context = context;
		projects = new ArrayList<ProjectList>();
	}

	public Activity getContext (){
		return context;
	}

	/* The function must return the view from position 'position'
	 * convertView is a list item that is no longer visible and can be converted
	 * @see android.widget.Adapter#getView(int, android.view.View, android.view.ViewGroup)
	 */
	@Override
	public View getView(int position, View convertView, ViewGroup list) {
		View element;

		// for efficiency we use 'convertView' so that we don't have to create each time a new View
		if (convertView == null) {
			LayoutInflater inflater = context.getLayoutInflater();
			element = inflater.inflate(R.layout.projectlist, null);

			// Use tags for efficiency!
			TagProject tagActivity = new TagProject();
			tagActivity.setProjectTitle((TextView)element.findViewById(R.id.projectTitle));
			element.setTag(tagActivity);
		}
		else element = convertView;

		// Use tags for efficiency!
		TagProject tagActivity = (TagProject) element.getTag();

		TextView textView = tagActivity.getProjectTitle();
		textView.setText(projects.get(position).getProjectTitle());
		tagActivity.setProjectTitle(textView);

		return element;
	}

	/* return the number of activities
	 * @see android.widget.Adapter#getCount()
	 */
	@Override
	public int getCount() {
		return projects.size ();
	}

	/* return the element from the specified position
	 * (non-Javadoc)
	 * @see android.widget.Adapter#getItem(int)
	 */
	@Override
	public Object getItem(int position) {
		return projects.get(position);

	}

	/* (non-Javadoc)
	 * @see android.widget.Adapter#getItemId(int)
	 */
	@Override
	public long getItemId(int position) {
		// each activity have a uniq ID
		return position;
	}

	/*
	 * Add new Activity to the ListView
	 */
	public void addActivity (String projectTitle) {
		ProjectList mActivityView = new ProjectList(projectTitle);
		projects.add (mActivityView);

		// this function determine the adapter to re-display the content of the list
		this.notifyDataSetChanged();
	}
}
